﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.TuiLing
{
    public class HttpClient
    {
        public string Url { get; set; }
        public string Content { get; set; }
        static CookieContainer Cookie = new CookieContainer();

        public string SysncRequest()
        {
            try
            {
                HttpWebRequest httpRequest = WebRequest.Create(Url) as HttpWebRequest;
                httpRequest.Method = "POST";
                httpRequest.ContentType = "application/json; charset=utf-8";
                httpRequest.CookieContainer = Cookie;
                httpRequest.Timeout = 1000 * 60 * 10;

                string requestBody;

                // 判断是否需要包装参数
                if (NeedWrapper(Url))
                {
                    // 对于需要包装的接口（如登录），使用包装格式
                    JObject jObj = new JObject();
                    jObj.Add("useragent", "ApiClient");
                    jObj.Add("rid", Guid.NewGuid().ToString().GetHashCode().ToString());
                    jObj.Add("parameters", Content);
                    jObj.Add("timestamp", DateTime.Now);
                    jObj.Add("v", "1.0");
                    requestBody = jObj.ToString();
                }
                else
                {
                    // 对于自定义接口，直接发送Content
                    requestBody = Content;
                }

                byte[] bytes = Encoding.UTF8.GetBytes(requestBody);
                httpRequest.ContentLength = bytes.Length;

                using (Stream reqStream = httpRequest.GetRequestStream())
                {
                    reqStream.Write(bytes, 0, bytes.Length);
                    reqStream.Flush();
                }

                using (WebResponse response = httpRequest.GetResponse())
                using (Stream repStream = response.GetResponseStream())
                using (var reader = new StreamReader(repStream, Encoding.UTF8))
                {
                    string result = reader.ReadToEnd();
                    return ValidateResult(result);
                }
            }
            catch (Exception ex)
            {
                return $"请求异常: {ex.Message}";
            }
        }

        /// <summary>
        /// 判断URL是否需要参数包装
        /// </summary>
        private bool NeedWrapper(string url)
        {
            // 登录服务需要包装，自定义服务不需要
            return url.Contains("AuthService.Login") ||
                   url.Contains("Kingdee.BOS.WebApi.ServicesStub");
        }

        private static string ValidateResult(string responseText)
        {
            if (responseText.StartsWith("response_error:"))
            {
                var failText = responseText.TrimStart("response_error:".ToCharArray());
            }
            return responseText;
        }
    }
    //public class HttpClient
    //{
    //    /// <summary>
    //    /// Seivice URL
    //    /// </summary>
    //    public string Url { get; set; }
    //    /// <summary>
    //    /// 内容
    //    /// </summary>
    //    public string Content { get; set; }
    //    /// <summary>
    //    /// Cookie，保证登录后，所有访问持有一个Cookie；
    //    /// </summary>
    //    static CookieContainer Cookie = new CookieContainer();

    //    /// <summary>
    //    /// HTTP访问
    //    /// </summary>
    //    public string SysncRequest()
    //    {
    //        HttpWebRequest httpRequest = HttpWebRequest.Create(Url) as HttpWebRequest;
    //        httpRequest.Method = "POST";
    //        httpRequest.ContentType = "application/json; charset=utf-8";
    //        httpRequest.CookieContainer = Cookie;
    //        httpRequest.Timeout = 1000 * 60 * 10;//10min

    //        using (Stream reqStream = httpRequest.GetRequestStream())
    //        {
    //            JObject jObj = new JObject();
    //            //jObj.Add("format", 1);
    //            jObj.Add("useragent", "ApiClient");
    //            jObj.Add("rid", Guid.NewGuid().ToString().GetHashCode().ToString());
    //            jObj.Add("parameters", Content);
    //            jObj.Add("timestamp", DateTime.Now);
    //            jObj.Add("v", "1.0");
    //            string sContent = jObj.ToString();
    //            var bytes = Encoding.UTF8.GetBytes(sContent);
    //            reqStream.Write(bytes, 0, bytes.Length);
    //            reqStream.Flush();
    //        }
    //        using (var repStream = httpRequest.GetResponse().GetResponseStream())
    //        {
    //            using (var reader = new StreamReader(repStream))
    //            {
    //                return ValidateResult(reader.ReadToEnd());
    //            }
    //        }
    //    }

    //    private static string ValidateResult(string responseText)
    //    {
    //        if (responseText.StartsWith("response_error:"))
    //        {
    //            var failText = responseText.TrimStart("response_error:".ToCharArray());
    //        }
    //        return responseText;
    //    }
    //}
}
